/**
 * 写出微信小程序中授权登录代码
 */
import {
  apiUrl
} from '../../config/index'
import EventBus from '../../utils/EventBus'
Page({
  data: {
    code: '',
    loginTip: '点击确认登录，登录小程序',
    logoUrl: apiUrl + '/gallery/0_logo.jpg',
  },
  onLoad() {

  },
  loginClick() {
    this.setData({
      loginTip: '正在登录，请稍后。。。'
    })
    wx.login({
      success: res => {
        this.code = res.code
        console.log('code:' + this.code)
        wx.request({
          url: apiUrl + "/user/loginByCode",
          data: {
            "code": this.code
          },
          method: 'POST',
          timeout: 0,
          success: (result) => {
            console.log(result)
            if (result.data.code == 1) {
              wx.setStorageSync('token', result.data.data.token)
              this.setData({
                loginTip: "登录成功，跳转中。。。"
              })
              EventBus.$emit('refreshUserInfo');
              wx.switchTab({
                url: '/pages/user/index',
              })
            } else {
              this.setData({
                loginTip: "登录失败"
              })
            }
          },
          fail: (err) => {
            console.err(err)
          },
          complete: (res) => {},
        })
      }
    })
  }
})